package concurrecy.util;


import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class JannaCyclicBarrier {
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private final int capacity;
    private volatile int count = 0;
    private volatile int version = 0;
    private Runnable barrierCommand;

    public JannaCyclicBarrier(int capacity, Runnable barrierCommand) {
        this.capacity = capacity;
        this.barrierCommand = barrierCommand;
    }

    public void await() throws InterruptedException, BrokenBarrierException {
        lock.lock();
        int v = version;
        try {
            int s = ++ count;
            if(s == capacity) {
                count = 0;
                version ++;
                condition.signalAll();
                barrierCommand.run();
            }
            while(v == version)
                condition.await();
        } finally {
            lock.unlock();
        }
    }
}

public class MyCyclicBarrierDemo {
    public static void main(String[] args) {
        JannaCyclicBarrier cyclicBarrier = new JannaCyclicBarrier(3, () -> {
            System.out.println("barrier action");
        });
        Random random = new Random();
        ExecutorService service = Executors.newCachedThreadPool();
        for(int i = 0; i < 6; i ++)
            service.execute(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(random.nextInt(10000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " await");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " exit");
            });
        service.shutdown();
    }
}
